# 搜索引擎模块：Tavily搜索
import os
import requests
import logging
from typing import Dict, Any, Optional
from app.config.settings import settings

logger = logging.getLogger(__name__)

def search_tavily(query: str, search_depth: str = "basic") -> Dict[str, Any]:
    """调用Tavily API进行搜索"""
    try:
        url = settings.tavily_base_url
        headers = {"Content-Type": "application/json"}
        payload = {
            "api_key": settings.tavily_api_key,
            "query": query,
            "search_depth": search_depth,
            "include_answer": True,
            "include_images": False,
            "include_raw_content": False,
            "max_results": 10
        }
        response = requests.post(url, json=payload, headers=headers, timeout=10)
        if response.status_code == 200:
            return response.json()
        else:
            logger.error(f"Tavily请求失败: {response.status_code}, {response.text}")
            return {"error": f"搜索请求失败: {response.status_code}", "message": response.text}
    except Exception as e:
        logger.error(f"Tavily搜索异常: {str(e)}")
        return {"error": f"搜索异常: {str(e)}"}

def format_search_results(result: Dict[str, Any]) -> str:
    """格式化Tavily搜索结果为文本"""
    if "error" in result:
        return f"搜索出错: {result['error']}"
    answer = result.get("answer", "")
    results = result.get("results", [])
    res_str = f"搜索答案: {answer}\n\n" if answer else ""
    if results:
        res_str += "相关搜索结果:\n"
        for i, item in enumerate(results[:3], 1):
            title = item.get("title", "无标题")
            content = item.get("content", "无内容")
            url = item.get("url", "无链接")
            res_str += f"{i}. {title}\n{content}\n来源: {url}\n\n"
    return res_str.strip()

def search_and_answer(query: str, user_question: str, llm=None) -> Optional[str]:
    """搜索并基于结果回答问题（可选LLM对象）"""
    result = search_tavily(query)
    if "error" in result:
        return None
    search_context = format_search_results(result)
    prompt = f"请基于以下搜索信息回答用户的问题，如果搜索信息中有影视作品相关内容，优先回答影视作品相关内容，请用中文回答，并确保答案准确、简洁、有用。\n\n用户问题: {user_question}\n\n搜索信息:\n{search_context}\n\n请基于上述信息提供一个完整、准确的回答:"
    if llm:
        response = llm.invoke(prompt)
        return response.content if hasattr(response, "content") else str(response)
    return search_context